package com.maidou.qiantai.common.utils.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @Author maidou
 * @Date 2024/3/15 1:58
 */
public class FileUploadUtil {

    public static String uploadImage(MultipartFile imageFile) {
        String uploadPath = "D:/javaEnvironment/javaUp/";

        // 创建日期文件夹
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/M/d");
        String dateFolder = currentDate.format(formatter);
        uploadPath += dateFolder + "/";

        // 创建目录
        File directory = new File(uploadPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }

        // 生成UUID文件名（不包含下划线）
        String uuid = UUID.randomUUID().toString().replace("-", "");

        // 获取文件后缀
        String fileName = imageFile.getOriginalFilename();
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));

        // 构建上传路径
        String uploadFileName = uuid + fileExtension;
        String filePath = uploadPath + uploadFileName;

        try {
            imageFile.transferTo(new File(filePath));
        } catch (IOException e) {
            return "文件上传失败：" + e.getMessage();
        }

        return filePath;
    }

    public static String deleteImage(String filePath){
//        String filePath = "D:/example.txt"; // 要删除的文件路径

        Path path = Paths.get(filePath);

        try {
            Files.delete(path);
            System.out.println("文件删除成功。");
        } catch (IOException e) {
            System.out.println("无法删除文件：" + e.getMessage());
        }
        return null;
    }


}

